<template>
    <div v-loading="loadingBoter">
        <el-button @click=" dialogTableVisible = true;" style="margin-bottom: 20px;">创建兑换码</el-button>
        <!-- <SearchForm>
            <template #header>
                <el-button @click=" dialogTableVisible = true;">创建兑换码</el-button>
            </template>
<el-form :model="searchForm" inline>
    <el-form-item>
        <el-input v-model="searchForm._id" clearable class="w-220px" placeholder="链接ID" />
    </el-form-item>
    <el-form-item>
        <el-select v-model="searchForm.status" placeholder="状态" clearable class="w-220px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
        </el-select>
    </el-form-item>
</el-form>
</SearchForm> -->
        <div class="page-card h-full" v-loading="loading">
            <el-table :data="tableData" style="width: 100%">
                <el-table-column prop="_id" label="ID" width="180" />
                <el-table-column prop="useStatus" label="是否使用">
                    <template #default="scope">
                        {{ scope.row.useStatus == 1 ? '已使用' : '未使用' }}
                    </template>
                </el-table-column>
                <el-table-column prop="proxy.userName" label="代理" />
                <el-table-column prop="goods.name" label="套餐" />
                <el-table-column prop="goods.price" label="价格" />
            </el-table>
            <Pagination :pageable="page" :handleSizeChange="handleSizeChange"
                :handleCurrentChange="handleCurrentChange" />
        </div>

        <el-dialog v-model="dialogTableVisible" title="创建兑换码" width="800">
            <el-form :model="addcodeform" :rules="rules" ref="addcoderef">
                <el-form-item label="选择ID" prop="proxyId" style="width: 300px;">

                    <el-input v-model="addcodeform.proxyId" placeholder="请输入代理ID" @blur="() => {
        getAgentsUserListApiFn(addcodeform.proxyId)
    }"></el-input>

                    <div>{{ shearProxyData.userName }}</div>
                </el-form-item>
                <el-form-item label="选择套餐类型" prop="taocan">
                    <el-select v-model="addcodeform.taocan" placeholder="请选择套餐类型" clearable style="width: 300px;">
                        <el-option :label="`${i.name}-¥${i.price}`" :value="i._id" v-for="i in payGoods" :key="i._id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="生成数量" prop="inputernum">
                    <el-input-number v-model="addcodeform.inputernum" :min="1" :max="1000" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogTableVisible = false">取消</el-button>
                    <el-button type="primary" @click="addCode">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import { getAiPayConfigApi } from '@/api/aliPay';
import { createQianChuanCodeApi, getQianChuanCodeListApi } from "@/api/qianchuan"
import { getAgentsUserListApi } from '@/api/user';
import { useTable } from '@/hooks/useTable';
import { ElMessage } from "element-plus";
import * as XLSX from 'xlsx'
import moment from 'moment'

const dialogTableVisible = ref(false);
const loadingBoter = ref(false);
const payGoods = ref<any>([])
const addcoderef = ref<any>(null)
const searchForm = reactive<any>({
    proxyId: '', goodsId: '',
    status: '',
    page: 1,
    pageSize: 10

});
const shearProxyData = ref<any>({})
const rules = {
    taocan: [
        {
            required: true,
            message: '请选择套餐类型',
            trigger: 'change',
        },
    ],
    inputernum: [{
        required: true,
        message: '请输入生成数量',
        trigger: 'blur',
    }],
    proxyId: [{
        required: true,
        message: '请输入代理ID',
        trigger: 'blur',
    }]
}
onMounted(() => {
    getAddAiConfig()
})
function getAddAiConfig() {
    getAiPayConfigApi({
        type: 'qianchuanQY',
        status: 1
    }).then(res => {
        console.log('resress', res);
        payGoods.value = res.data.list
    })
}
function getAgentsUserListApiFn(_id) {
    if (!_id) {
        ElMessage.error('请输入代理ID')
        addcodeform.proxyId = ''
        shearProxyData.value = {}
        return
    }
    getAgentsUserListApi({
        _id
    }).then(res => {
        if (res.data.list.length) {
            shearProxyData.value = res.data.list[0]
        } else {
            ElMessage.error('代理ID不存在')
            addcodeform.proxyId = ''
            shearProxyData.value = {}
        }
    })
}
const { tableData, page, loading, resetParams, getList, handleCurrentChange, handleSizeChange } =
    useTable({
        apiFn: getQianChuanCodeListApi,
        params: searchForm,
        // callback
    });
async function addCode() {
    if (!addcoderef) return

    await addcoderef.value.validate((valid, fields) => {
        if (valid) {
            loadingBoter.value = true
            createQianChuanCodeApi(addcodeform).then(res => {
                console.log('res', res.data)
                saveAsExcel(res.data)
                dialogTableVisible.value = false
            }).finally(() => {
                loadingBoter.value = false
            })
        } else {
            console.log('error submit!', fields)
        }
    })

}

function saveAsExcel(obj) {

    const workbook = XLSX.utils.book_new();
    const newDatasw = [
        ['兑换码', '套餐', '价格'],
        ...obj.map((item) => {
            return [item.id, item.good, item.price]
        })
    ]

    const worksheet = XLSX.utils.aoa_to_sheet(newDatasw);
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    XLSX.writeFile(workbook, `千川兑换码-${obj[0].good}-¥${obj[0].price}-${obj[0].proxy}X${obj.length}${moment().format('YYYY-MM-DD HH:mm:ss')}.xlsx`);




    return true
}

const addcodeform = reactive<any>({
    taocan: '',
    inputernum: 1,
    proxyId: ''
})


</script>